package com.qmx.qmxapp;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zhouwei.library.CustomPopWindow;
import com.qmx.qmxapp.base.BaseActivity;
import com.qmx.qmxapp.constant.AppConstant;
import com.qmx.qmxapp.fragment.ContactsFragment;
import com.qmx.qmxapp.fragment.FolderFragment;
import com.qmx.qmxapp.fragment.MeetingFragment;
import com.qmx.qmxapp.fragment.MineFragment;
import com.qmx.qmxapp.token.TokenManager;
import com.qmx.qmxapp.utils.SocketUtil;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.CommonPagerTitleView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.widget.Toast.LENGTH_SHORT;

/**
 * @author chengxiangtong
 * @date 2018/10/8
 */

public class MainActivity extends BaseActivity implements SocketUtil.SocketDataCallback {

    private static final String[] CHANNELS = new String[]{"会议", "通讯录", "文件夹", "我"};
    private static final int[] checked = new int[]{R.drawable.customer_service_fill, R.drawable.read_fill, R.drawable.folder_open_fill, R.drawable.mine};
    private static final int[] unchecked = new int[]{R.drawable.uncustomer_service_fill, R.drawable.unread_fill, R.drawable.unfolder_open_fill, R.drawable.unmine};
    private List<String> mDataList = Arrays.asList(CHANNELS);
    private ViewPager mViewPager;
    private List<Fragment> mFragments = new ArrayList<Fragment>();
    private MagicIndicator magicIndicator;

    private MyAdapter myAdapter;

    @BindView(R.id.iv_add)
    ImageView iv_add;
    @BindView(R.id.rv_main)
    RelativeLayout rv_main;

    private CustomPopWindow mCustomPopWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        mViewPager = findViewById(R.id.view_pager);
        myAdapter = new MyAdapter(getSupportFragmentManager(), mFragments);
        mViewPager.setAdapter(myAdapter);
        initFragments();
        initMagicIndicator();
        setVisibility(0);

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                magicIndicator.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                magicIndicator.onPageSelected(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                magicIndicator.onPageScrollStateChanged(state);
            }
        });
        SocketUtil.getInstance();
        SocketUtil.getInstance().setSocketDataCallback(this);

        getClientId();

    }

    private void getClientId() {
        Log.d("getClientId=", "getClientId: 调用");
        LinkedHashMap<Object, Object> hashMap = new LinkedHashMap<>();
        hashMap.put("token", TokenManager.getInstance().getAuthModel().getToken());
        SocketUtil.getInstance().sendSocketData("auth@login", hashMap);
        hashMap.clear();

    }

    private void initFragments() {
        MeetingFragment meetingFragment = new MeetingFragment();
        mFragments.add(meetingFragment);
        ContactsFragment contactsFragment = new ContactsFragment();
        mFragments.add(contactsFragment);
        FolderFragment folderFragment = new FolderFragment();
        mFragments.add(folderFragment);
        MineFragment mineFragment = new MineFragment();
        mFragments.add(mineFragment);

    }

    private void initMagicIndicator() {
        magicIndicator = findViewById(R.id.magic_indicator);
        magicIndicator.setBackgroundColor(Color.BLACK);
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int i) {
                CommonPagerTitleView commonPagerTitleView = new CommonPagerTitleView(context);
                // load custom layout
                View customLayout = LayoutInflater.from(context).inflate(R.layout.bottom_pager_title_layout, null);
                final ImageView titleImg = (ImageView) customLayout.findViewById(R.id.title_img);
                final TextView titleText = (TextView) customLayout.findViewById(R.id.title_text);
                titleImg.setImageResource(checked[i]);
                titleText.setText(mDataList.get(i));
                commonPagerTitleView.setContentView(customLayout);
                setVisibility(i);
                commonPagerTitleView.setOnPagerTitleChangeListener(new CommonPagerTitleView.OnPagerTitleChangeListener() {
                    @Override
                    public void onSelected(int i, int totalCount) {
                        titleText.setTextColor(Color.WHITE);
                        titleText.setTextSize(10);
                        titleImg.setImageResource(checked[i]);
                    }

                    @Override
                    public void onDeselected(int i, int totalCount) {
                        titleText.setTextColor(Color.LTGRAY);
                        titleText.setTextSize(10);
                        titleImg.setImageResource(unchecked[i]);
                    }

                    @Override
                    public void onLeave(int i, int i1, float v, boolean b) {
                        //                        titleImg.setScaleX(1.1f + (0.8f - 1.1f) * v);
                        //                        titleImg.setScaleY(1.1f + (0.8f - 1.1f) * v);
                    }

                    @Override
                    public void onEnter(int index, int totalCount, float enterPercent, boolean leftToRight) {
                        //                        titleImg.setScaleX(0.8f + (1.1f - 0.8f) * enterPercent);
                        //                        titleImg.setScaleY(0.8f + (1.1f - 0.8f) * enterPercent);
                    }
                });

                commonPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mViewPager.setCurrentItem(i);
                        setVisibility(i);
                    }
                });

                return commonPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                return null;
            }
        });
        magicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(magicIndicator, mViewPager);

    }


    public void setVisibility(int pos) {
        if (pos == 0) {
            rv_main.setVisibility(View.VISIBLE);
        } else {
            rv_main.setVisibility(View.GONE);
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
    }

    @OnClick(R.id.iv_add)
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_add:
                showPopMenu();
                break;
        }
    }


    private void showPopMenu() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_main_menu, null);
        //处理popWindow 显示内容
        handleLogic(contentView);
        //创建并显示popWindow
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .create()
                .showAsDropDown(iv_add, -100, 40);
    }

    /**
     * 处理弹出显示内容、点击事件等逻辑
     *
     * @param contentView
     */
    private void handleLogic(View contentView) {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCustomPopWindow != null) {
                    mCustomPopWindow.dissmiss();
                }
                String showContent = "";
                switch (v.getId()) {
                    case R.id.ll_scan_code:
                        showContent = MainActivity.this.getResources().getString(R.string.app_scan_code);
                        break;
                    case R.id.ll_share_img:
                        showContent = MainActivity.this.getResources().getString(R.string.app_share_load_link);
                        break;
                }
                Toast.makeText(MainActivity.this, showContent, LENGTH_SHORT).show();
            }
        };
        contentView.findViewById(R.id.ll_scan_code).setOnClickListener(listener);
        contentView.findViewById(R.id.ll_share_img).setOnClickListener(listener);

    }

    @Override
    public void socketDataCallback(int code, JSONObject j) {
        Log.i("==socketDataCallback", code + "");
        saveClientId(j);
    }

    private class MyAdapter extends FragmentStatePagerAdapter {
        private List<Fragment> mFragments;

        public MyAdapter(FragmentManager fm, List<Fragment> mFragments) {
            super(fm);
            this.mFragments = mFragments;
        }

        @Override
        public Fragment getItem(int position) {
            Fragment fragment = null;
            fragment = mFragments.get(position);
            return fragment;
        }

        @Override
        public int getCount() {
            return mDataList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mDataList.get(position);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SocketUtil.getInstance().clearSendSocketData();
        finish();
    }
}
